<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 3] 3.9 Abstract Classes and Interfaces</TITLE>
<META NAME="author" CONTENT="David Flanagan">
<META NAME="date" CONTENT="Thu Jul 31 15:50:00 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Java in a Nutshell">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java in a Nutshell" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch03_08.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 3<br>Classes and Objects in Java</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch03_10.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9">3.9 Abstract Classes and Interfaces</A></h2>

<P CLASS=para>
<A NAME="CH3.ABSTRACT.CLA1"></A><A NAME="CH3.CLASSES3"></A>In
<A HREF="ch03_08.htm#JNUT2-CH-3-EX-14">Example 3.14</A>
we declared our <tt CLASS=literal>Circle</tt> class to be part of a package
named <tt CLASS=literal>shapes</tt>.  Suppose we plan to implement a number
of shape classes: <tt CLASS=literal>Rectangle</tt>, <tt CLASS=literal>Square</tt>,
<tt CLASS=literal>Ellipse</tt>, <tt CLASS=literal>Triangle</tt>, and so on.  We'll give
all of these shape classes our two basic <tt CLASS=literal>area()</tt> and
<tt CLASS=literal>circumference()</tt> methods.  Now, to make it easy to
work with an array of shapes, it would be
helpful if all our shape classes have a common superclass,
<tt CLASS=literal>Shape</tt>.  We want <tt CLASS=literal>Shape</tt> to encapsulate
whatever features all our shapes have in common.  In this
case, they have in common the <tt CLASS=literal>area()</tt> and
<tt CLASS=literal>circumference()</tt> methods.  But our generic
<tt CLASS=literal>Shape</tt> class can't actually implement these methods,
since it doesn't represent any actual shape.  Java handles
this case with abstract methods.

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9.1">Abstract Methods</A></h3>

<P CLASS=para>
<A NAME="CH3.ABSTRACT.MET1"></A><A NAME="CH3.METHODS4"></A>Java lets us define a method without implementing it by
making the method <tt CLASS=literal>abstract</tt>.  An <tt CLASS=literal>abstract</tt>
method has no body; it simply has a signature definition
followed by a semicolon.
[13]
Here are the rules about <tt CLASS=literal>abstract</tt> methods, 
and the <tt CLASS=literal>abstract</tt> classes that contain them:

<blockquote class=footnote>
<P CLASS=para>[13] 
An <tt CLASS=literal>abstract</tt> method in Java is something like a
"pure virtual function" in C++ (i.e., a virtual function
that is declared <tt CLASS=literal>= 0</tt>).  In C++, a class that
contains a pure virtual function is called an "abstract
class" and may not be instantiated.  The same is true of
Java classes that contain <tt CLASS=literal>abstract</tt> methods.
</blockquote>
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>Any class with an <tt CLASS=literal>abstract</tt> method is automatically
<tt CLASS=literal>abstract</tt> itself, and must be declared as such.

<P>
<li CLASS=listitem>A class may be declared <tt CLASS=literal>abstract</tt> even if it has no
<tt CLASS=literal>abstract</tt> methods.  This prevents it from being
instantiated. 

<P>
<li CLASS=listitem>An <tt CLASS=literal>abstract</tt> class cannot be instantiated.

<P>
<li CLASS=listitem>A subclass of an <tt CLASS=literal>abstract</tt> class can be instantiated
if it overrides each of the <tt CLASS=literal>abstract</tt> methods of its
superclass and provides an implementation (i.e., a method
body) for all of them.

<P>
<li CLASS=listitem>If a subclass of an <tt CLASS=literal>abstract</tt> class does not
implement all of the <tt CLASS=literal>abstract</tt> methods it inherits,
that subclass is itself <tt CLASS=literal>abstract</tt>.

<P>
</UL>
<P CLASS=para>
That description of the <tt CLASS=literal>abstract</tt> keyword was pretty
abstract!
<A HREF="ch03_09.htm#JNUT2-CH-3-EX-15">Example 3.15</A>
is more concrete.  It shows an <tt CLASS=literal>abstract</tt>
<tt CLASS=literal>Shape</tt> class and two non-<tt CLASS=literal>abstract</tt> subclasses
of it.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-3-EX-15">Example 3.15: An Abstract Class and Subclasses</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
public abstract class Shape {
    public abstract double area();
    public abstract double circumference();
}
class Circle extends Shape {
    protected double r;
    protected static final double PI = 3.14159265358979323846;
    public Circle() { r = 1.0; }
    public Circle(double r) { this.r = r; }
    public double area() { return PI * r * r; }
    public double circumference() { return 2 * PI * r; }
    public double getRadius() { return r; }
}
class Rectangle extends Shape {
    protected double w, h;
    public Rectangle() { w = 0.0; h = 0.0; }
    public Rectangle(double w, double h) { this.w = w;  this.h = h; }
    public double area() { return w * h; }
    public double circumference() { return 2 * (w + h); }
    public double getWidth() { return w; }
    public double getHeight() { return h; }
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
Note that the <tt CLASS=literal>abstract</tt> methods in <tt CLASS=literal>Shape</tt> have a
semicolon right after their parentheses.  There are no curly
braces, and no method body is defined.  Using the classes
defined in
<A HREF="ch03_09.htm#JNUT2-CH-3-EX-15">Example 3.15</A>,
we can now write code like this:

<DIV CLASS=screen>
<P>
<PRE>
Shape[] shapes = new Shape[3];          // Create an array to hold shapes.
shapes[0] = new Circle(2.0);            // Fill in the array...
shapes[1] = new Rectangle(1.0, 3.0);
shapes[2] = new Rectangle(4.0, 2.0);
double total_area = 0;
for(int i = 0; i &lt; shapes.length; i++)
    total_area += shapes[i].area();     // Compute the area of the shapes.
</PRE>
</DIV>

<P CLASS=para>
There are two important points to notice here:

<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>Subclasses of <tt CLASS=literal>Shape</tt> can be assigned to elements of
an array of <tt CLASS=literal>Shape</tt>.  No cast is necessary.

<P>
<li CLASS=listitem>You can invoke the <tt CLASS=literal>area()</tt> and
<tt CLASS=literal>circumference()</tt> methods for <tt CLASS=literal>Shape</tt> objects,
even though <tt CLASS=literal>Shape</tt> does not define a body for these
methods, because <tt CLASS=literal>Shape</tt> declared them
<tt CLASS=literal>abstract</tt>.  If <tt CLASS=literal>Shape</tt> did not declare them at
all, the code would cause a compilation error.

<P>
</UL>
<P CLASS=para>
</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9.2">Interfaces</A></h3>

<P CLASS=para>
<A NAME="CH3.DATA.TYPES1"></A><A NAME="CH3.INTERFACES1"></A>Let's extend our <tt CLASS=literal>shapes</tt> package further.  Suppose we
now want to implement a number of shapes that can be drawn
on the screen.  We could define an abstract
<tt CLASS=literal>DrawableShape</tt> class, and then implement various
subclasses of it, such as <tt CLASS=literal>DrawableCircle</tt>,
<tt CLASS=literal>DrawableRectangle</tt>, and so on.  This would work fine.

<P CLASS=para>
But suppose we want our drawable shape types to support the
<tt CLASS=literal>area()</tt> and <tt CLASS=literal>circumference()</tt> methods.  We
don't want to have to re-implement these methods, so we'd
like to make <tt CLASS=literal>DrawableCircle</tt> a subclass of
<tt CLASS=literal>Circle</tt>, for example, and <tt CLASS=literal>DrawableRectangle</tt> a
subclass of <tt CLASS=literal>Rectangle</tt>.  But classes in Java can only
have one superclass.  If <tt CLASS=literal>DrawableCircle</tt> extends
<tt CLASS=literal>Circle</tt>, then it cannot also extend
<tt CLASS=literal>DrawableShape</tt>!
[14]

<blockquote class=footnote>
<P CLASS=para>[14] 
C++ allows classes to have more than one superclass, using
a technique known as "multiple inheritance." Multiple
inheritance opens up a can of worms, so Java replaces it
with what many believe is a more elegant solution.
</blockquote>
<P CLASS=para>
Java's solution to this problem is called an
<I CLASS=emphasis>interface</I>.  An interface looks a lot like an abstract
class, except that it uses the keyword <tt CLASS=literal>interface</tt>
instead of the words <tt CLASS=literal>abstract</tt> and <tt CLASS=literal>class</tt>.
<A HREF="ch03_09.htm#JNUT2-CH-3-EX-16">Example 3.16</A>
shows an interface named <tt CLASS=literal>Drawable</tt>.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-3-EX-16">Example 3.16: An Interface Definition</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
public interface Drawable {
    public void setColor(Color c);
    public void setPosition(double x, double y);
    public void draw(DrawWindow dw);
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
While an <tt CLASS=literal>abstract</tt> class may define some <tt CLASS=literal>abstract</tt> methods and
some non-<tt CLASS=literal>abstract</tt> methods, all the methods defined within an
interface are implicitly <tt CLASS=literal>abstract</tt>.  We've omitted
the <tt CLASS=literal>abstract</tt> keyword in this example, but it is
perfectly legal to use it if you want to belabor the
abstractness of interface methods.  A further restriction on
interfaces is that any variables declared in an interface
must be <tt CLASS=literal>static</tt> and <tt CLASS=literal>final</tt>--that is, they must
be constants.

<P CLASS=para>
So what can we do with an interface?  Just as a class
<tt CLASS=literal>extends</tt> its superclass, it also optionally <tt CLASS=literal>implements</tt>
an interface.  <tt CLASS=literal>implements</tt> is a Java keyword that can
appear in a class declaration following the
<tt CLASS=literal>extends</tt> clause.  <tt CLASS=literal>implements</tt> should be
followed by the name of the interface that the class
implements.  In order to implement an interface, a class
must first declare the interface in an <tt CLASS=literal>implements</tt>
clause, and then it
must provide an implementation (i.e., a body) for all of the
<tt CLASS=literal>abstract</tt> methods of the interface.
[15]

<blockquote class=footnote>
<P CLASS=para>[15] 
This is the real difference between multiple inheritance in
C++ and interfaces in Java.  In C++, a class can inherit
method implementations from more than one superclass.  In
Java, a class can inherit actual implementations only from
one superclass.  It can inherit additional <tt CLASS=literal>abstract</tt>
methods from interfaces, but it must provide its own
implementation of those methods.  It is rare, however, to
actually be able to use C++ multiple inheritance to inherit
useful, non-trivial implementations from more than one class.
The elegance and simplicity of Java's interface more than
compensate for the inability to inherit implementations from
more than one class.
</blockquote>
<P CLASS=para>
<A HREF="ch03_09.htm#JNUT2-CH-3-EX-17">Example 3.17</A>
shows how we can define a <tt CLASS=literal>DrawableRectangle</tt> class
that extends our <tt CLASS=literal>Rectangle</tt> class and implements the
<tt CLASS=literal>Drawable</tt> interface we defined in
<A HREF="ch03_09.htm#JNUT2-CH-3-EX-16">Example 3.16</A>.
The example assumes that a <tt CLASS=literal>Color</tt> class and a
<tt CLASS=literal>DrawWindow</tt> class are defined elsewhere, and that
<tt CLASS=literal>DrawWindow</tt> knows how to convert floating-point
coordinates to pixel coordinates and knows how to draw
primitive shapes.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-3-EX-17">Example 3.17: Implementing an Interface</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
public class DrawableRectangle extends Rectangle implements Drawable {
    // New instance variables
    private Color c;
    private double x, y;
    // A constructor
    public DrawableRectangle(double w, double h) { super(w, h); }
    // Here are implementations of the Drawable methods.
    // We also inherit all the public methods of Rectangle.
    public void setColor(Color c) { this.c = c; }
    public void setPosition(double x, double y) { this.x = x; this.y = y; }
    public void draw(DrawWindow dw) { 
        dw.drawRect(x, y, w, h, c);
    }
}
</PRE>
</DIV>

</DIV>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9.3">Using Interfaces</A></h3>

<P CLASS=para>
Suppose we implement <tt CLASS=literal>DrawableCircle</tt> and
<tt CLASS=literal>DrawableSquare</tt> just as we implemented
<tt CLASS=literal>DrawableRectangle</tt> in
<A HREF="ch03_09.htm#JNUT2-CH-3-EX-17">Example 3.17</A>.
As we saw earlier, instances of these classes can be treated
as instances of the abstract <tt CLASS=literal>Shape</tt> class.  They can
also be treated as instances of the <tt CLASS=literal>Drawable</tt> interface.
<A HREF="ch03_09.htm#JNUT2-CH-3-EX-18">Example 3.18</A>
demonstrates this.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-3-EX-18">Example 3.18: Casting Objects to Their Interface Type</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
Shape[] shapes = new Shape[3];          // Create an array to hold shapes
Drawable[] drawables = new Drawable[3]; // and an array to hold drawables.
// Create some drawable shapes.
DrawableCircle dc = new DrawableCircle(1.1);
DrawableSquare ds = new DrawableSquare(2.5);
DrawableRectangle dr = new DrawableRectangle(2.3, 4.5);
// The shapes can be assigned to both arrays.
shapes[0] = dc;   drawables[0] = dc;
shapes[1] = ds;   drawables[1] = ds;
shapes[2] = dr;   drawables[2] = dr;
// Compute total area and draw the shapes by invoking 
// the Shape and the Drawable abstract methods.
double total_area = 0;
for(int i = 0; i &lt; shapes.length; i++) {
    total_area += shapes[i].area();    // Compute the area of the shapes.
    drawables[i].setPosition(i*10.0, i*10.0);
    drawables[i].draw(draw_window);    // Assume draw_window defined somewhere.
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
What this example demonstrates is that interfaces are data
types in Java, just as classes are, and that when a class
implements an interface, instances of that class can be
assigned to variables of the interface type.  Don't
interpret this example to imply that you must assign a
<tt CLASS=literal>DrawableRectangle</tt> object to a <tt CLASS=literal>Drawable</tt>
variable before you can invoke the <tt CLASS=literal>draw()</tt> method or
that you must assign it to a <tt CLASS=literal>Shape</tt> variable before
you can invoke the <tt CLASS=literal>area()</tt> method.
<tt CLASS=literal>DrawableRectangle</tt> defines <tt CLASS=literal>draw()</tt> and
inherits <tt CLASS=literal>area()</tt> from its <tt CLASS=literal>Rectangle</tt>
superclass, and so you can always invoke these methods.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9.4">Implementing Multiple Interfaces</A></h3>

<P CLASS=para>
Suppose we wanted shapes that could be scaled to be larger
or smaller.  One way we could do this is by defining a
<tt CLASS=literal>Scalable</tt> interface and implementing subclasses of
<tt CLASS=literal>DrawableRectangle</tt> and the other classes.  To do this,
though, the new subclass would have to implement both the
<tt CLASS=literal>Drawable</tt> interface and the <tt CLASS=literal>Scalable</tt>
interface.
This is no problem.  You may specify a list of
comma-separated interfaces in the <tt CLASS=literal>implements</tt> clause
of any class:

<DIV CLASS=screen>
<P>
<PRE>
public class DrawableScalableRectangle extends DrawableRectangle
                implements Drawable, Scalable {
    // The methods of the Scalable interface must be implemented here.
}
</PRE>
</DIV>

<P CLASS=para>
When a class implements more than one interface, it means
simply that it must provide an implementation for all of the
abstract methods in all of its interfaces.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9.5">Constants in Interfaces</A></h3>

<P CLASS=para>
As we noted above, constants may appear in interface
definitions.  What does it mean to implement an interface
that contains constants?  It
simply means that the class that implements the interface
"inherits" the constants (in a sense) and can use them as if
they were defined directly in the class.  There is no need
to prefix them with the name of the interface, and there is
no need to provide an "implementation" of the constants:

<DIV CLASS=screen>
<P>
<PRE>
class A { static final int CONSTANT1 = 3; }
interface B { static final int CONSTANT2 = 4; }
class C implements B {
    void f() { 
        int i = A.CONSTANT1;  // Have to use the class name here.
        int j = CONSTANT2;    // No class name here, because we implement
    }                         // the interface that defines this constant.
}
</PRE>
</DIV>

<P CLASS=para>
When you have a set of constants used by more than one class
within a package (for example, a port number and other
protocol constants used by a client and server), it is
convenient to define them in an interface that contains no
abstract <tt CLASS=literal>methods</tt>.  Then, any class that wants to use
those constants needs only to declare that it implements the
interface.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9.6">Extending Interfaces</A></h3>

<P CLASS=para>
Interfaces can have sub-interfaces, just as classes can have subclasses.  A
sub-interface inherits all the abstract methods and
constants of its super-interface, and may define new
abstract methods and constants.  Interfaces are different
from classes in one very important way, however. 

<P CLASS=para>
An interface can extend more than one interface at a time:

<DIV CLASS=screen>
<P>
<PRE>
public interface Transformable extends Scalable, Rotateable, Reflectable { }
public interface DrawingObject extends Drawable, Transformable { }
public class Shape implements DrawingObject { ... }
</PRE>
</DIV>

<P CLASS=para>
An interface that extends more than one interface inherits
all the abstract methods and constants from each of those
interfaces, and may define its own additional abstract methods
and constants.  A class that implements such an interface
must implement the abstract methods defined in the interface
itself as well as all the abstract methods inherited from
all the super-interfaces.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-3-SECT-9.7">Marker Interfaces</A></h3>

<P CLASS=para>
Another technique that is sometimes useful is to define an
interface that is entirely empty.  A class can implement
this interface to provide additional information about
itself.  The <tt CLASS=literal>Cloneable</tt> interface in
<tt CLASS=literal>java.lang</tt> is an example of this type of "marker
interface."  It defines no methods, but serves simply to
identify the class as one that will allow its internal state
to be cloned by the <tt CLASS=literal>clone()</tt> method of the
<tt CLASS=literal>Object</tt> class.  In Java 1.1,
<tt CLASS=literal>java.io.Serializable</tt> is another such marker
interface.  You can test whether a class implements a marker
interface (or any interface) using the <tt CLASS=literal>instanceof</tt>
operator.

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch03_08.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch03_10.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Data Hiding and Encapsulation</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>C++ Features Not Found in Java</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
